package com.jiuyou.clientController.comment;

import com.alibaba.fastjson.JSONObject;
import com.jiuyou.clientController.base.ClientBaseController;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.ciModel.snapshot.SnapshotRequest;
import com.qcloud.cos.model.ciModel.snapshot.SnapshotResponse;
import com.qcloud.cos.region.Region;
import com.ruoyi.comment.domain.Comment;
import com.ruoyi.comment.service.ICommentService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.controller.HandleVideoSrc;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.domain.model.LoginMember;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.order.domain.StoreProductOrder;
import com.ruoyi.order.service.IStoreProductOrderService;
import com.ruoyi.product.service.IStoreProductService;
import com.ruoyi.store.domain.Store;
import com.ruoyi.store.service.IStoreService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 评价
 *
 * @author jiuyou
 */
@Api(tags = {"C端评价相关"})
@RestController
@RequestMapping("/client/comment")
public class commentClientController extends ClientBaseController
{
    private static final Logger log = LoggerFactory.getLogger(commentClientController.class);

    @Autowired
    private ICommentService commentService;
    @Autowired
    private IStoreProductOrderService orderService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private ISysConfigService configService;
    /**
     * 查询评价记录列表
     */
    @ApiOperation(value = "查询评价记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "当前第几页",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize",value = "每页几条数据",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "storeId",value = "门店id",dataType = "Long"),
            @ApiImplicitParam(name = "productId",value = "商品id",dataType = "Long"),
    })
    @PostMapping("/list")
    public AjaxResult list(Long storeId,Long productId,Integer pageNum,Integer pageSize,Long pid)
    {
        Comment commentParam=new Comment();
        commentParam.setStoreId(storeId);
        commentParam.setProductId(productId);
        commentParam.setPid(pid);
        startPage();
        List<Comment> list = commentService.selectCommentList(commentParam);
        TableDataInfo tableDataInfo =getDataTable(list);
        list= (List<Comment>) tableDataInfo.getRows();
        List<JSONObject> resultList=new ArrayList<JSONObject>();
        for (Comment comment:list) {
            JSONObject jso= new JSONObject();
            jso.put("commentId",comment.getId());
            jso.put("memberNickName",comment.getMemberNickName());
            jso.put("memberHeadImg",comment.getMemberHeadImg());
            jso.put("commentContent",comment.getCommentContent());
            jso.put("commentImages",comment.getCommentImages());
            jso.put("commentVideo",comment.getCommentVideo());
            jso.put("videoCover",comment.getVideoCover());
            jso.put("storeContent",comment.getStoreContent());
            jso.put("storeLevel",comment.getStoreLevel());
            jso.put("effectLevel",comment.getEffectLevel());
            jso.put("environmentLevel",comment.getEnvironmentLevel());
            jso.put("serviceLevel",comment.getServiceLevel());
            jso.put("createTime", DateUtils.dateTime(comment.getCreateTime()));
            jso.put("orderId",comment.getOrderId());

            Comment commentParam2=new Comment();
            commentParam2.setStoreId(comment.getStoreId());
            commentParam2.setProductId(comment.getProductId());
            commentParam2.setPid(comment.getId());

            List<Comment> list2 = commentService.selectCommentList(commentParam2);
            jso.put("chlidList",list2);

            resultList.add(jso);
        }
        tableDataInfo.setRows(resultList);
        return AjaxResult.success(tableDataInfo);
    }

    /**
     * 获取评价记录详细信息
     */
    @ApiOperation(value = "获取评价详情")
    @ApiImplicitParam(name = "id",value = "评价id",dataType = "Long")
    @PostMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        Comment comment=commentService.selectCommentById(id);
        if(null==comment){
            return AjaxResult.error("参数错误");
        }
        JSONObject jso= new JSONObject();
        jso.put("memberNickName",comment.getMemberNickName());
        jso.put("memberHeadImg",comment.getMemberHeadImg());
        jso.put("commentContent",comment.getCommentContent());
        jso.put("commentImages",comment.getCommentImages());
        jso.put("productName",comment.getProductName());
        jso.put("commentVideo",comment.getCommentVideo());
        jso.put("videoCover",comment.getVideoCover());
        jso.put("storeContent",comment.getStoreContent());
        jso.put("effectLevel",comment.getEffectLevel());
        jso.put("environmentLevel",comment.getEnvironmentLevel());
        jso.put("serviceLevel",comment.getServiceLevel());
        jso.put("storeLevel",comment.getStoreLevel());
        jso.put("orderId",comment.getOrderId());
        jso.put("createTime", DateUtils.dateTime(comment.getCreateTime()));
        return AjaxResult.success(jso);
    }

    /**
     * 新增评价记录
     */
    @ApiOperation(value = "添加评价详情")
    @PostMapping
    public AjaxResult add(@ApiParam @RequestBody Comment comment)
    {
        LoginMember loginMember= getLoginMember();
        if(null==loginMember){
            return AjaxResult.error("登录状态异常");
        }

        StoreProductOrder order = orderService.selectStoreProductOrderById(comment.getOrderId());
        comment.setProductId(order.getProductId());
        Member member=loginMember.getMember();
        comment.setMemberId(member.getId());
        comment.setMemberHeadImg(member.getHeadImg());
        comment.setMemberNickName(member.getNickName());
        BigDecimal de = new BigDecimal("0");
        if(comment.getEffectLevel() != null){
            de = de.add(comment.getEffectLevel());
        }
        if(comment.getEnvironmentLevel() != null){
            de = de.add(comment.getEnvironmentLevel());
        }
        if(comment.getServiceLevel() != null){
            de = de.add(comment.getServiceLevel());
        }
        de = de.divide(new BigDecimal("3"),2,BigDecimal.ROUND_HALF_UP);
        comment.setStoreLevel(de);
        comment.setProductName(order.getProductName());
        comment.setStoreId(order.getStoreId());
        comment.setId(null);

        if(StringUtils.isNotEmpty(comment.getCommentVideo())){
            Map<String, String> val = configService.getVal();
            comment.setVideoCover(HandleVideoSrc.handle(val.get("key"),val.get("id"),val.get("region"),val.get("bn"),comment.getCommentVideo()));
        }
        commentService.insertComment(comment);
        order.setCommentId(comment.getId());
        order.setCommentState(DicConstants.SYS_Y.getCode());
       // order.setOrderState(DicConstants.ORDER_STATE_OrderClose.getCode());
        orderService.updateStoreProductOrder(order);
        //更新门店评价
        Long storeId=order.getStoreId();
        JSONObject avgJso=commentService.storeCommentAvg(storeId);
        Store store=new Store();
        store.setId(storeId);

        store.setEffectLevel(avgJso.getBigDecimal("EFFECTLEVEL"));
        store.setEnvironmentLevel(avgJso.getBigDecimal("ENVIRONMENTLEVEL"));
        store.setServiceLevel(avgJso.getBigDecimal("SERVICELEVEL"));
        BigDecimal STORELEVEL=store.getEffectLevel().add(store.getEnvironmentLevel()).add(store.getServiceLevel()).divide(new BigDecimal("3"),2,BigDecimal.ROUND_HALF_UP);
        store.setStoreLevel(STORELEVEL);
        storeService.updateStore(store);
        return toAjax(1);
    }


    /**
     * 删除评价记录
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {

        Long loginMemberId=getLoginMemberId();
        if(null==loginMemberId){
            return AjaxResult.error("登录状态异常");
        }
        return toAjax(commentService.logicDeleteComment(ids,DicConstants.BUSINESS_Manager.getCode(), SecurityUtils.getUserId()));
    }
}
